package com.example.redis.interceptor;

import com.example.redis.annoa.AutoIdempotent;
import com.example.redis.exception.IdempotentException;
import com.example.redis.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/*@Component*/
public class IdempotentInterceptor  implements HandlerInterceptor {

    @Autowired
    TokenService tokenService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(! (handler instanceof HandlerMethod)){
            return true;
        }
        Method method = ((HandlerMethod) handler).getMethod();
        AutoIdempotent idempotent = method.getAnnotation(AutoIdempotent.class);
        if(idempotent != null){
            try{
                return tokenService.checkToken(request);
            }catch(IdempotentException e){
                throw new IdempotentException("token不存在");
            }

        }
        return true;
    }
}
